package com.example.demo.controller;

import com.example.demo.dto.CourseDetailsDTO;
import com.example.demo.model.ApiResponse;
import com.example.demo.model.Course;
import com.example.demo.model.User;
import com.example.demo.model.Course.Status;
import com.example.demo.repository.CourseRepository;
import com.example.demo.repository.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.Arrays;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;
import com.example.demo.dto.CourseDTO;

@RestController
@RequestMapping("/api/courses")
public class CourseController {

    @Autowired
    private CourseRepository courseRepository;

    @Autowired
    private UserRepository userRepository;

    @GetMapping
    public ResponseEntity<ApiResponse<List<CourseDTO>>> getAllCourses(
            @RequestParam(name = "teacherId", required = false) Integer teacherId,
            @RequestParam(required = false) String role) {
        List<Course> courses = filterCourses(teacherId, role);
        List<CourseDTO> courseDTOs = courses.stream()
                .map(c -> new CourseDTO(
                        c.getCourseId(),
                        c.getCourseName(),
                        c.getTeacher().getUserId(),
                        c.getTeacher().getUsername(),
                        c.getStartTime(),
                        c.getEndTime(),
                        c.getStatus().name(),
                        c.getDescription(),
                        c.getStudents().stream().map(User::getUsername).collect(Collectors.toList()),
                        c.getOpenday()
                ))
                .collect(Collectors.toList());
        return ResponseEntity.ok(ApiResponse.success(courseDTOs));
    }

    private List<Course> filterCourses(Integer teacherId, String role) {
        if (teacherId != null && role != null && role.equalsIgnoreCase("teacher")) {
            return courseRepository.findByTeacherUserId(teacherId);
        } else if (teacherId != null) {
            return courseRepository.findCoursesByTeacherIdForToday(teacherId);
        } else {
            return courseRepository.findAll();
        }
    }

    @PostMapping
    public ResponseEntity<ApiResponse<Course>> createCourse(@RequestBody CourseDTO courseDTO) {
        // 检查教师是否存在
        if (!userRepository.existsById(courseDTO.getTeacherId())) {
            return ResponseEntity.status(HttpStatus.NOT_FOUND)
                    .body(ApiResponse.error(HttpStatus.NOT_FOUND.value(), "教师不存在"));
        }
        // 创建 Course 对象并设置教师
        Course course = new Course();
        course.setCourseName(courseDTO.getCourseName());
        // 处理时间字段类型转换
        course.setStartTime(courseDTO.getStartTime());
        course.setEndTime(courseDTO.getEndTime());

        // 增强枚举转换容错
        try {
            course.setStatus(Status.valueOf(courseDTO.getStatus()));
        } catch (IllegalArgumentException e) {
            return ResponseEntity.badRequest().body(ApiResponse.error(HttpStatus.BAD_REQUEST.value(),
                    "无效的状态值，可选值：" + Arrays.toString(Status.values())));
        }
        course.setDescription(courseDTO.getDescription());

        // 设置教师
        User teacher = userRepository.findById(courseDTO.getTeacherId())
                .orElseThrow(() -> new RuntimeException("教师不存在"));
        course.setTeacher(teacher);

        // 保存课程
        Course savedCourse = courseRepository.save(course);
        return new ResponseEntity<>(ApiResponse.success(savedCourse), HttpStatus.CREATED);
    }

    @PutMapping("/{id}")
    public ResponseEntity<ApiResponse<Course>> updateCourse(@PathVariable Integer id, @RequestBody CourseDTO courseDTO) {
        // 添加ID一致性校验
        if (!id.equals(courseDTO.getCourseId())) {
            return ResponseEntity.badRequest().body(ApiResponse.error(HttpStatus.BAD_REQUEST.value(), "ID不一致"));
        }

        // 根据teacherId从数据库中获取User对象
        Integer teacherId = courseDTO.getTeacherId();
        Optional<User> teacherOptional = userRepository.findById(teacherId);
        if (!teacherOptional.isPresent()) {
            return ResponseEntity.badRequest().body(ApiResponse.error(HttpStatus.BAD_REQUEST.value(), "教师不存在"));
        }
        User teacher = teacherOptional.get();

        // 创建Course对象并设置属性
        Course course = new Course();
        course.setCourseId(id);
        course.setCourseName(courseDTO.getCourseName());
        course.setOpenday(courseDTO.getOpenday());
        course.setTeacher(teacher);
        course.setStartTime(courseDTO.getStartTime());
        course.setEndTime(courseDTO.getEndTime());
        course.setStatus(Course.Status.valueOf(courseDTO.getStatus()));
        course.setDescription(courseDTO.getDescription());

        // 处理学生列表，这里可以根据需求完善
        // course.setStudents(students);

        Course updatedCourse = courseRepository.save(course);
        return ResponseEntity.ok(ApiResponse.success(updatedCourse));
    }

    @DeleteMapping("/{id}")
    public ResponseEntity<ApiResponse<Void>> deleteCourse(@PathVariable Integer id) {
        courseRepository.deleteById(id);
        return ResponseEntity.ok(ApiResponse.success(null));
    }
}